package com.micangcaihang.micang.mvp.task.ui;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;

import com.afollestad.materialdialogs.MaterialDialog;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.micangcaihang.common.base.fragment.BaseFragment;
import com.micangcaihang.common.utils.BeanUtils;
import com.micangcaihang.common.utils.KeyboardUtils;
import com.micangcaihang.common.utils.StringUtils;
import com.micangcaihang.common.utils.ToastUtils;
import com.micangcaihang.micang.R;
import com.micangcaihang.micang.adapter.DAgentPriceAdapter;
import com.micangcaihang.micang.adapter.DNewTowerPriceAdapter;
import com.micangcaihang.micang.databinding.FragmentTaskPriceSurveyBinding;
import com.micangcaihang.micang.entity.TaskPriceSurveyEntity;
import com.micangcaihang.micang.mvp.task.contract.TaskPriceSurveyContract;
import com.micangcaihang.micang.mvp.task.presenter.TaskPriceSurveyPresenter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * <pre>
 *     author : Fandy
 *     e-mail : fandayongfly@gmail.com
 *     time   : 2017/07/24
 *     update : 2017/07/24
 *     desc   : 价格调查
 *     version: 1.0
 * </pre>
 */

public class TaskPriceSurveyFragment extends BaseFragment<TaskPriceSurveyPresenter,
        FragmentTaskPriceSurveyBinding> implements TaskPriceSurveyContract.View {
    private TaskPriceSurveyEntity mOldRequest;
    private TaskPriceSurveyEntity mPriceSurveyEntity;
    /**
     * n新楼价格适配器
     */
    private DNewTowerPriceAdapter mNewTowerPriceAdapter;
    /**
     * 中介2个月快速成交价适配器
     */
    private DAgentPriceAdapter mAgentPriceAdapter;
    private String id;
    private int currentPost;
    private int deleteType;
    private boolean isNetSuccess;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        id = getArguments().getString("id");
    }

    public static TaskPriceSurveyFragment newInstance(String id) {
        Bundle args = new Bundle();
        TaskPriceSurveyFragment fragment = new TaskPriceSurveyFragment();
        args.putString("id", id);
        fragment.setArguments(args);
        return fragment;
    }

    /**
     * 获取资源文件布局
     *
     * @return 资源布局文件layout
     */
    @Override
    protected int getLayoutId() {
        return R.layout.fragment_task_price_survey;
    }

    /**
     * 初始化view
     *
     * @param rootView 资源布局view
     */
    @Override
    public void initView(View rootView) {
        super.initView(rootView);
        mViewBinding.recyclerViewAgentPrice.setLayoutManager(new LinearLayoutManager(_mActivity));
        mViewBinding.recyclerViewNewTowerPrice.setLayoutManager(new LinearLayoutManager(_mActivity));
    }

    /**
     * 初始化对象
     */
    @Override
    protected void initData() {
        super.initData();
        mOldRequest = new TaskPriceSurveyEntity();
        mOldRequest.setId(id);
        mPriceSurveyEntity = new TaskPriceSurveyEntity();
        mPriceSurveyEntity.setId(id);
        mNewTowerPriceAdapter = new DNewTowerPriceAdapter(R.layout.item_new_tower_price, new ArrayList<>());
        mAgentPriceAdapter = new DAgentPriceAdapter(R.layout.item_agent_price, new ArrayList<>());
        mViewBinding.recyclerViewAgentPrice.setAdapter(mAgentPriceAdapter);
        mViewBinding.recyclerViewNewTowerPrice.setAdapter(mNewTowerPriceAdapter);
    }

    /**
     * 简单页面无需mvp就不用管此方法即可,完美兼容各种实际场景的变通
     */
    @Override
    public void initPresenter() {
        super.initPresenter();
        mPresenter.setId(id);
    }

    /**
     * 初始化按钮监听
     */
    @Override
    protected void initListener() {
        mViewBinding.setClickHandler(new ClickHandler());
        mViewBinding.recyclerViewAgentPrice.addOnItemTouchListener(new OnItemChildClickListener() {
            @Override
            public void onSimpleItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                new MaterialDialog.Builder(_mActivity)
                        .content("确定删除中介2个月快速成交价该条目吗?")
                        .positiveText("确定")
                        .negativeText("取消")
                        .onPositive((dialog, which) -> {
                            deleteType = 2;
                            currentPost = position;
                            if ("0".equals(mAgentPriceAdapter.getData().get(position).getEvaluate_id())) {
                                mAgentPriceAdapter.remove(position);
                                mOldRequest.getZhongjie().remove(position);
                            } else {
                                mPresenter.deletePriceData(id, mAgentPriceAdapter.getData().get(position).getEvaluate_id());
                            }
                        })
                        .show();
            }
        });
        mViewBinding.recyclerViewNewTowerPrice.addOnItemTouchListener(new OnItemChildClickListener() {
            @Override
            public void onSimpleItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                new MaterialDialog.Builder(_mActivity)
                        .content("确定删除新楼价格该条目吗?")
                        .positiveText("确定")
                        .negativeText("取消")
                        .onPositive((dialog, which) -> {
                            deleteType = 1;
                            currentPost = position;
                            if ("0".equals(mNewTowerPriceAdapter.getData().get(position).getEvaluate_id())) {
                                mNewTowerPriceAdapter.remove(position);
                                mOldRequest.getXinlou().remove(position);
                            } else {
                                mPresenter.deletePriceData(id, mNewTowerPriceAdapter.getData().get(position).getEvaluate_id());
                            }
                        })
                        .show();
            }
        });
    }


    /**
     * 返回价格调查信息
     *
     * @param entity
     */
    @Override
    public void returnPriceSurveyData(TaskPriceSurveyEntity entity) {
        isNetSuccess = true;
        List<TaskPriceSurveyEntity.XinLou> xinLous = entity.getXinlou();
        List<TaskPriceSurveyEntity.ZhongJie> zhongJies = entity.getZhongjie();
        mPriceSurveyEntity = entity;
        mPriceSurveyEntity.setId(id);
        mOldRequest.setId(id);
        mOldRequest.getXinlou().clear();
        mOldRequest.getZhongjie().clear();
        try {
            mOldRequest.getXinlou().addAll(BeanUtils.deepCopy(entity.getXinlou()));
            mOldRequest.getZhongjie().addAll(BeanUtils.deepCopy(entity.getZhongjie()));
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        mAgentPriceAdapter.setNewData(zhongJies);
        mNewTowerPriceAdapter.setNewData(xinLous);
    }

    /**
     * 删除价格成功
     */
    @Override
    public void deletePriceSuccess() {
        switch (deleteType) {
            case 1:
                mNewTowerPriceAdapter.remove(currentPost);
                mOldRequest.getXinlou().remove(currentPost);
                break;
            case 2:
                mAgentPriceAdapter.remove(currentPost);
                mOldRequest.getZhongjie().remove(currentPost);
                break;
        }
    }

    public class ClickHandler {

        public void onSave(View view) {
            saveData();
        }

        public void onBusinessEvaluateOne(View view) {
            KeyboardUtils.hideSoftInput(_mActivity);
            if (checkXinLou()) return;
            TaskPriceSurveyEntity.XinLou bean = new TaskPriceSurveyEntity.XinLou();
            bean.setEstimate_fee("");
            bean.setReference_name("");
            bean.setUnit_price("");
            bean.setEvaluate_id("0");
            mNewTowerPriceAdapter.addData(bean);
            TaskPriceSurveyEntity.XinLou xinLou = new TaskPriceSurveyEntity.XinLou();
            xinLou.setEstimate_fee("");
            xinLou.setReference_name("");
            xinLou.setUnit_price("");
            xinLou.setEvaluate_id("0");
            mOldRequest.getXinlou().add(xinLou);
            mViewBinding.recyclerViewNewTowerPrice.setFocusableInTouchMode(true);
            mViewBinding.recyclerViewNewTowerPrice.smoothScrollToPosition(mNewTowerPriceAdapter.getItemCount() - 1);
        }

        public void onBusinessEvaluateTwo(View view) {
            KeyboardUtils.hideSoftInput(_mActivity);
            if (checkZhongJie()) return;
            TaskPriceSurveyEntity.ZhongJie bean = new TaskPriceSurveyEntity.ZhongJie();
            bean.setContacts("");
            bean.setEvaluate_source("");
            bean.setReference_name("");
            bean.setUnit_price("");
            bean.setEvaluate_id("0");
            mAgentPriceAdapter.addData(bean);
            TaskPriceSurveyEntity.ZhongJie zhongJie = new TaskPriceSurveyEntity.ZhongJie();
            zhongJie.setContacts("");
            zhongJie.setEvaluate_source("");
            zhongJie.setReference_name("");
            zhongJie.setUnit_price("");
            zhongJie.setEvaluate_id("0");
            mOldRequest.getZhongjie().add(zhongJie);
            mViewBinding.recyclerViewAgentPrice.setFocusableInTouchMode(true);
            mViewBinding.recyclerViewAgentPrice.smoothScrollToPosition(mAgentPriceAdapter.getItemCount() - 1);
        }
    }

    private boolean checkXinLou() {
        boolean isWrite = false;
        for (int i = 0; i < mNewTowerPriceAdapter.getData().size(); i++) {
            TaskPriceSurveyEntity.XinLou xinLou = mNewTowerPriceAdapter.getData().get(i);
            if (StringUtils.isEmpty(xinLou.getUnit_price())) {
                isWrite = true;
                break;
            }
        }
        if (isWrite) {
            ToastUtils.showLong("请填写新楼价格单价");
            return true;
        }
        return false;
    }

    private boolean checkZhongJie() {
        boolean isWrite = false;
        for (int i = 0; i < mAgentPriceAdapter.getData().size(); i++) {
            TaskPriceSurveyEntity.ZhongJie xinLou = mAgentPriceAdapter.getData().get(i);
            if (StringUtils.isEmpty(xinLou.getUnit_price())) {
                isWrite = true;
                break;
            }
        }
        if (isWrite) {
            ToastUtils.showLong("请填写中介2个月快速成交价单价");
            return true;
        }
        return false;
    }

    /**
     * 开始保存数据请求
     */
    public void saveData() {
//        if (checkXinLou()) return;
//        if (checkZhongJie()) return;
        setSaveData();
        if (mPriceSurveyEntity.toString().equals(mOldRequest.toString())) {
            ToastUtils.showLong("您没有更改任何信息，无需保存");
            return;
        }
        isNetSuccess = false;
        mPresenter.savePriceSurveyData(mPriceSurveyEntity);
    }

    /**
     * 判断是否保存过数据 没有的话点击保存去保存
     *
     * @return 是否保存当前页面数据
     */
    public boolean isSaveData() {
        //如果请求错误则返回true
        if (!isNetSuccess) {
            return true;
        }
        setSaveData();
        if (mPriceSurveyEntity.toString().equals(mOldRequest.toString())) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 设置请求数据
     */
    private void setSaveData() {

    }
}
